<template>
  <div class="all-trail">
    <div class="search">
      <el-form :model="form" ref="ruleFormRef" label-width="auto">
        <el-row :gutter="0" style="margin-bottom: 10px">
          <el-col :span="6">
            <el-form-item label="所属课程">
              <el-select
                v-model="form.lessonName"
                placeholder="请选择所在班级"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in lessonList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="试听班级">
              <el-select
                v-model="form.className"
                placeholder="请选择所在班级"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in beginClassList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="上课老师">
              <el-select
                v-model="form.teacherName"
                placeholder="请选择上课老师"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in teacherList"
                  :key="item.id"
                  :label="item.nickName"
                  :value="item.id"
                >
                  {{ item.nickName }}{{ !item.isJob ? "(已离职)" : "" }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery(ruleFormRef)"
              >重置</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- <div class="manage">
      <el-button plain @click="handleExport">导出</el-button>
    </div> -->
    <!-- 表格 -->
    <div class="students-table">
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column label="学员姓名" fixed="left" width="200">
          <template #default="scope">
            <div>
              <router-link
                :to="'/registrar/studentsDetails/detail/' + scope.row.studentId"
                class="link-type"
              >
                <span
                  style="margin-right: 10px; color: #67c23a; cursor: pointer"
                  >{{ scope.row.name }}</span
                >
              </router-link>
              <el-icon v-if="scope.row.gender == '1'" style="color: #fb6465"
                ><Female
              /></el-icon>
              <el-icon
                v-else-if="scope.row.gender == '0'"
                style="color: #4791ed"
                ><Male
              /></el-icon>
              <span
                style="
                  padding: 1px 8px;
                  font-size: 12px;
                  border-radius: 2px;
                  margin-left: 5px;
                  color: rgb(237.5, 189.9, 118.5);
                  border: 2px solid rgb(237.5, 189.9, 118.5);
                  font-weight: bolder;
                "
              >
                {{
                  scope.row.stage === 1
                    ? "意向"
                    : scope.row.stage === 2
                    ? "在读"
                    : scope.row.stage === 3
                    ? "跟进"
                    : scope.row.stage === 4
                    ? "报读"
                    : scope.row.stage === 5
                    ? "历史"
                    : "未知"
                }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          property="mobile"
          label="手机号"
          fixed="left"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="courseNameC"
          label="试听课程"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          label="试听时间"
          show-overflow-tooltip
          :formatter="formatName"
          width="180"
        >
          <template #default="scope"
            ><div>{{ scope.row.classDate }}</div>
            {{ scope.row.classStartTime }}-{{ scope.row.classEndTime }}
          </template>
        </el-table-column>
        <el-table-column
          property="teacherName"
          label="上课老师"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />

        <el-table-column
          property="classHourPay"
          label="授课课时"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="creatorName"
          label="学员创建人"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="counselorName"
          label="跟进人"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="managementName"
          label="学管师"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="applicationTime"
          label="报名时间"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          label="是否报名"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
          fixed="right"
        >
          <template #default="scope">
            {{ scope.row.isApplication == "0" ? "否" : "是" }}
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
          fixed="right"
        >
          <template #default="scope">
            {{
              scope.row.type === 1 || scope.row.type === 4
                ? "已预约"
                : scope.row.type === 2 || scope.row.type === 3
                ? "已体验"
                : scope.row.type === 5
                ? "未到课"
                : scope.row.type === 6
                ? "已取消"
                : "未知状态"
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <div v-if="![6, 2, 3].includes(scope.row.type)">
              <el-button
                link
                type="primary"
                @click="toTrail(scope.row)"
                v-hasPermi="['sales:trail:reload']"
              >
                重约
              </el-button>
              <el-button
                v-show="scope.row.type !== 5"
                link
                type="primary"
                @click="toCancelAudition(scope.row)"
                v-hasPermi="['sales:trail:cancel']"
              >
                取消
              </el-button>
            </div>
            <div v-else>-</div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="total"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        @pagination="toGetTrailList"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeMount } from "vue";
import Pagination from "@/components/Pagination/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getBeginClassList,
  getTeacherList,
  getLessonList,
  auditionList,
  cancelAudition,
} from "@/api/studentManagement/index.js";
const { proxy } = getCurrentInstance();

//表单
const ruleFormRef = ref(null);
const form = ref({
  className: "",
  lessonName: "",
  teacherName: "",
});
//搜索
const handleQuery = () => {
  pageNum.value = 1;

  toGetTrailList();
};
//重置
// const resetQuery = () => {
//     console.log('11111');
//     ruleFormRef.value.resetFields()
// }
const resetQuery = () => {
  form.value = {
    className: "",
    lessonName: "",
    teacherName: "",
  };
  pageNum.value = 1;
  toGetTrailList();
};

//班级老师
const teacherList = ref([]);
const toGetTeacherList = async () => {
  try {
    const res = await getTeacherList({});
    if (res.code == 200) {
      teacherList.value = res.data;
    }
  } catch (error) {
    console.error("获取班级老师下拉列表失败:", error);
  }
};
onMounted(toGetTeacherList);

//获取课程列表
const lessonList = ref([]);
const toGetLessonList = async () => {
  try {
    const res = await getLessonList({
      pageNum: 1,
      pageSize: 9999,
      open:1
    });
    if (res.code == 200) {
      lessonList.value = res.rows;
    }
  } catch (error) {
    console.error("获取课程列表失败:", error);
  }
};
onBeforeMount(toGetLessonList);
//获取上课班级列表
const beginClassList = ref([]);
const toGetBeginClassList = async () => {
  try {
    const res = await getBeginClassList({
      pageNum: 1,
      pageSize: 9999,
    });
    if (res.code == 200) {
      beginClassList.value = res.rows;
    }
  } catch (error) {
    console.error("获取学生的信息失败:", error);
  }
};
onBeforeMount(toGetBeginClassList);
//分页器
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
//获取表格数据
const loading = ref(true);
const tableData = ref([]);
const toGetTrailList = async () => {
  loading.value = true;
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    courseId: form.value.lessonName,
    classId: form.value.className,
    teacher: form.value.teacherName,
  };
  try {
    const res = await auditionList(params);
    if (res.code == 200) {
      total.value = res.total;
      tableData.value = res.rows;
      loading.value = false;
      tableData.value.forEach((item) => {
        if (item.classDate) {
          const dateTimeString = item.classDate;
          const date = new Date(dateTimeString.replace(" ", "T")); // 创建日期对象
          // 获取年、月、日
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，所以加1
          const day = String(date.getDate()).padStart(2, "0");
          item.classDate = `${year}-${month}-${day}`;
        }
      });
    }
  } catch (error) {
    console.error("获取学生列表失败:", error);
  }
};
onMounted(toGetTrailList);
//表格没有数据显示'-'
const formatName = (row, column, cellValue) => {
  return cellValue === "" || cellValue === null ? "-" : cellValue;
};

//取消试听
const toCancelAudition = (row) => {
  ElMessageBox.confirm(
    "取消后，该学员将移出试听班级的安排课次，确认取消？",
    "取消试听",
    {
      confirmButtonText: "取消预约",
      cancelButtonText: "再想想",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        const res = await cancelAudition({
          id: row.id,
        });
        if (res.code == 200) {
          pageNum.value = 1;
          toGetTrailList();
          ElMessage({
            type: "success",
            message: "取消成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: "操作失败",
          });
        }
      } catch (error) {
        console.error("操作失败:", error);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已放弃取消操作",
      });
    });
};
//重约前往试听课页面
const router = useRouter();
const toTrail = (row) => {
  router.push({
    name: "trail",
    params: { studentsId: row.studentId },
  });
};
</script>

<style lang="scss" scoped>
.all-trail {
  padding-bottom: 30px;
  .search {
    margin-top: 20px;
  }
  .manage {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    height: 40px;
  }
}
</style>